package com.lanyou.esb.servicemix.monitor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import com.lanyou.esb.datadictionary.BundleType;
import com.lanyou.esb.datadictionary.EnableType;
import com.lanyou.esb.servicemix.bean.Bundle;
import com.lanyou.esb.servicemix.monitor.rest.MonitorService;
import com.lanyou.esb.servicemix.monitor.rest.RestFactory;
import com.lanyou.esb.servicemix.monitor.rest.bean.BundleResponse;
import com.lanyou.esb.servicemix.monitor.rest.bean.Property;

/**
 * 导出ServiceMix容器的核心BUNDLE
 * 
 * @author Davey.wu
 */
public class ExportBundles {
	private static String BUNDLE_LOCATION_NAME = "Bundle Location";
	/** 核心BUNDLE的最大ID(包括基础bundle:CookProxy) **/
	private static int COOKPROXY_ID = 270;
	private static int CORE_MAX_ID = 280;
	private static String SQL_HEAD = "INSERT INTO t_esb_bu_bundles(BUNDLE_ID,"
			+ "BUNDLE_NO," + "BUNDLE_NAME," + "BUNDLE_TYPE," + "VERSION_NO,"
			+ "STATUS," + "BUNDLE_LOCATION," + "BUNDLE_JAR_NAME,"
			+ "IS_ENABLE," + "CREATOR," + "CREATED_DATE," + "MODIFIER,"
			+ "LAST_UPDATED_DATE" + ") VALUES";
	private static FastDateFormat FASTDATEFORMAT = FastDateFormat
			.getInstance("yyyy-MM-dd HH:mm:ss");
	private static FastDateFormat FASTDATEFORMAT_NOSPACE = FastDateFormat
			.getInstance("yyyyMMddHHmmss");

//	public static void main(String[] args) {
//		System.out.println("开始导出BUNDLE，请稍后。。。");
//		Date now = new Date();
//		String script = getScript();
//		String fileName = "C:\\bundle_sql\\bundles_script_"
//				+ FASTDATEFORMAT_NOSPACE.format(now) + ".sql";
//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(new File(fileName));
//			out.write(script.getBytes());
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} finally {
//			if (out != null) {
//				try {
//					out.close();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
//		System.out.println("导出完毕");
//		System.out.println("文件路径：" + fileName);
//	}

	private static String getScript() {
		ESBServer esbServer = new ESBServer();
		esbServer.setServerAddres("172.28.16.90");
		esbServer.setPort(8181);

		RestFactory restFactory = new RestFactory(esbServer);
		MonitorService monitorService = restFactory.getMonitorService();

		BundleResponse bundleResponse = monitorService.getBundles();
		List<Bundle> bundles = bundleResponse.getData();
		Date now = new Date();
		String user = "SYSTEM";
		StringBuilder script = new StringBuilder();
		script.append("DELETE FROM t_esb_bu_bundles;\n");
		for (Bundle bundle : bundles) {
			if (!isCore(bundle)) {
				continue;
			}
			String location = "";
			String jarName = "";
			BundleResponse detial = monitorService
					.getBundleById(bundle.getId());
			List<Property> props = detial.getData().get(0).getProps();
			for (Property t : props) {
				if (BUNDLE_LOCATION_NAME.equals(t.getKey())) {
					location = t.getValue().toString();
					break;
				}
			}
			if (StringUtils.isNotBlank(location)) {
				jarName = location.substring(location.indexOf(":") + 1);
				if (jarName.indexOf("/") > 0) {
					jarName = jarName.substring(jarName.indexOf("/") + 1);
					jarName = jarName.replace("/", ".");
					jarName += ".jar";
				}
			}
			System.out.println(location+"---------"+jarName);
			script.append("DELETE FROM t_esb_bu_bundles WHERE BUNDLE_NAME=\""
					+ bundle.getName() + "\" AND VERSION_NO=\""
					+ bundle.getVersion() + "\";\n");
			String bundleType = BundleType.CORE.ValueCode;
			if (COOKPROXY_ID == bundle.getId()) {
				bundleType = BundleType.BASE.ValueCode;
			}
			String version = bundle.getVersion();
			if (version != null && version.length() > 20) {
				version = version.substring(0, 20);
			}
			StringBuilder builder = new StringBuilder();
			builder.append("(");
			builder.append("\"")
					.append(UUID.randomUUID().toString().replaceAll("-", ""))
					.append("\"").append(",");
			builder.append(bundle.getId()).append(",");
			builder.append("\"").append(bundle.getName()).append("\"")
					.append(",");
			builder.append("\"").append(bundleType).append("\"").append(",");

			builder.append("\"").append(version).append("\"").append(",");
			builder.append("\"").append(bundle.getState()).append("\"")
					.append(",");
			builder.append("\"").append(location).append("\"").append(",");// location
			builder.append("\"").append(jarName).append("\"").append(",");// jar
			builder.append("\"").append(EnableType.ENABLE.ValueCode)
					.append("\"").append(",");
			builder.append("\"").append(user).append("\"").append(",");
			builder.append("\"").append(FASTDATEFORMAT.format(now))
					.append("\"").append(",");
			builder.append("\"").append(user).append("\"").append(",");
			builder.append("\"").append(FASTDATEFORMAT.format(now))
					.append("\"");
			builder.append(")");
			builder.append(";\n");
			script.append(SQL_HEAD);
			script.append(builder.toString());
		}
		return script.toString();
	}

	private static boolean isCore(Bundle bundle) {
		if (bundle.getId() > CORE_MAX_ID) {
			return false;
		}
		return true;
	}

}
